package internationalenergytradingplatform.controller.Transporter;

import internationalenergytradingplatform.VO.BuyerLoginVO;
import internationalenergytradingplatform.VO.TransporterLoginVO;
import internationalenergytradingplatform.constant.MessageConstant;
import internationalenergytradingplatform.context.BaseContext;
import internationalenergytradingplatform.dao.TransporterAccountMapper;
import internationalenergytradingplatform.exception.*;
import internationalenergytradingplatform.pojo.BuyerAccount;
import internationalenergytradingplatform.pojo.TransporterAccount;
import internationalenergytradingplatform.properties.JwtProperties;
import internationalenergytradingplatform.result.Result;
import internationalenergytradingplatform.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@CrossOrigin
@RequestMapping("/transporter-account")
public class TransporterAccountController {

    @Autowired
    TransporterAccountMapper transporterAccountMapper;

    @Autowired
    private JwtProperties jwtProperties;

    /**
     *
     * @author yingfeng
     * @date 2024/3/27 16:20
     运输商登录
     */
    @PostMapping("/login")
    public Result<TransporterLoginVO> login(@RequestBody TransporterAccount transporterAccount){
        String tele = transporterAccount.getTele();
        String password = transporterAccount.getPassword();
        TransporterAccount transporterByTele = transporterAccountMapper.getCompanyByTele(tele);
        //如果账号不存在
        if(transporterByTele == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        //对密码md5加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //密码错误
        if (!password.equals(transporterByTele.getPassword())) {
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        //账号被锁定
        if(transporterByTele.getTransporterAccountStatus() != 1) {
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("tele", transporterByTele.getTele());
        String token = JWTUtil.createJWT(
                jwtProperties.getAdminSecretKey(),//令牌的key
                jwtProperties.getAdminTtl(),//令牌的有效时间
                claims);

        //将运输商信息写入VO中
        TransporterLoginVO transporterLoginVO = TransporterLoginVO.builder()
                .tele(transporterByTele.getTele())
                .password(transporterByTele.getPassword())
                .companyName(transporterByTele.getCompanyName())
                .unifiedCreditCode(transporterByTele.getUnifiedCreditCode())
                .qualificationCertificateImage(transporterByTele.getQualificationCertificateImage())
                .avatarImage(transporterByTele.getAvatarImage())
                .avatarImage(transporterByTele.getAvatarImage())
                .balance(transporterByTele.getBalance())
                .token(token)
                .build();
        log.info("登录结果：{}", transporterLoginVO);
        return Result.success(transporterLoginVO);
    }

    /**
     * 运输商注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody TransporterAccount transporterAccount) {
        log.info("运输时注册信息：{}", transporterAccount);
        //判断必要属性是否填写完整
        if(transporterAccount.getTele() == null || transporterAccount.getTele().trim().isEmpty() ) {
            throw new MissingKeyAttributeException(MessageConstant.MISSING_KEY_ATTRIBUTES + ":tele");
        }
        if(transporterAccount.getCompanyName() == null || transporterAccount.getCompanyName().trim().isEmpty() ) {
            throw new MissingKeyAttributeException(MessageConstant.MISSING_KEY_ATTRIBUTES + ":companyName");
        }
        if(transporterAccount.getPassword() == null || transporterAccount.getPassword().trim().isEmpty()) {
            throw new MissingKeyAttributeException(MessageConstant.MISSING_KEY_ATTRIBUTES + ":password");
        }
        if(transporterAccount.getUnifiedCreditCode() == null || transporterAccount.getUnifiedCreditCode().trim().isEmpty()) {
            throw new MissingKeyAttributeException(MessageConstant.MISSING_KEY_ATTRIBUTES + ":unifiedCreditCode");
        }
        if(transporterAccount.getQualificationCertificateImage() == null || transporterAccount.getQualificationCertificateImage().trim().isEmpty()) {
            throw new MissingKeyAttributeException(MessageConstant.MISSING_KEY_ATTRIBUTES + ":qualificationCertificateImage");
        }
        if(transporterAccount.getAvatarImage() == null || transporterAccount.getAvatarImage().trim().isEmpty()) {
            throw new MissingKeyAttributeException(MessageConstant.MISSING_KEY_ATTRIBUTES + ":avatarImage");
        }

        //查找手机号是否已经被注册
        TransporterAccount companyByTele = transporterAccountMapper.getCompanyByTele(transporterAccount.getTele());
        if(companyByTele!= null){//手机号已经被注册了
            throw new AccountAlreadyExistsException(MessageConstant.CANNOT_REGISTER_AN_EXISTING_ACCOUNT_AGAIN);
        }

        //对密码进行md5加密
        transporterAccount.setPassword(DigestUtils.md5DigestAsHex(transporterAccount.getPassword().getBytes()));
        //set默认值
        transporterAccount.setTransporterAccountStatus(1);
        transporterAccount.setBalance(0.0);

        //插入数据库
        transporterAccountMapper.insertTransporter(transporterAccount);
        return Result.success();
    }

    /**
     * 运输商更改信息
     */
    @PutMapping("/updateTransporterInfo")
    public Result<TransporterAccount> updateTransporterInfo(@RequestBody TransporterAccount transporterAccount) {
        //获取当前登录的运输商id
        String transporterId = BaseContext.getCurrentId();
        transporterAccount.setTele(transporterId);
        transporterAccountMapper.updateTransporterInfo(transporterAccount);
        return Result.success();
    }

    /**
     * 获取运输商的全部信息
     */
    @GetMapping("/getTransporterInfo")
    public Result<TransporterAccount> getTransporterInfo() {
        //获取运输商的id
        String transporterId = BaseContext.getCurrentId();
        TransporterAccount companyByTele = transporterAccountMapper.getCompanyByTele(transporterId);
        return Result.success(companyByTele);
    }
}
